package com.doublefish.doublefishrobot.ui.home.s5;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.home.bean.DeviceBean;
import com.doublefish.doublefishrobot.ui.home.widget.ProgressView;
import com.doublefish.doublefishrobot.utils.AppCacheUtil;
import com.doublefish.doublefishrobot.utils.BrightnessTools;
import com.doublefish.doublefishrobot.utils.DebounceOnClickListener;
import com.doublefish.doublefishrobot.utils.MessageEvent;
import com.doublefish.doublefishrobot.utils.ble.bean.ModeConstant;
import com.doublefish.doublefishrobot.utils.socket.DFS5ProtocolMaker;
import com.doublefish.doublefishrobot.utils.socket.SocketManager;
import com.doublefish.doublefishrobot.widget.CommonDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者:dugaofeng on 2024/12/30 10:37
 */
public class S5ModeBallActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView titleTV;

    @BindView(R.id.tv_right)
    TextView rightTV;

    @BindView(R.id.tv_device_name)
    TextView deviceNameTV;

    @BindView(R.id.rl_content)
    ProgressView progressView;
    @BindView(R.id.tv_hint_time)
    TextView hintTimeTV;
    @BindView(R.id.tv_time)
    TextView timeTV;
    @BindView(R.id.tv_hint_count)
    TextView hintCountTV;
    @BindView(R.id.tv_count)
    TextView countTV;

    @BindView(R.id.tv_start)
    TextView startTV;
    @BindView(R.id.tv_stop)
    TextView stopTV;

    @BindView(R.id.tv_unload)
    TextView unloadTV;

    private Timer timer = null;
    private int ballTime;   //已经运行的时间
    private int offsetCount = 0;

    private String modeName;
    private char[] data;
    private boolean isTime = false;
    private int time = 0;
    private int count = 0;
    private float oriBright = 0.5f;  //原始的亮度
    private int lockCounter = 0;  //锁屏的计数器

    public static Intent makeIntent(Activity activity, String modeName, boolean isTime, int time, int count, char[] data) {
        Intent intent = new Intent(activity, S5ModeBallActivity.class);
        intent.putExtra("isTime", isTime);
        intent.putExtra("time", time);
        intent.putExtra("count", count);
        intent.putExtra("modeName", modeName);
        intent.putExtra("data", data);
        return intent;
    }

    @Override
    protected void onDestroy() {
        stopBall();
        stopTimer();
        unRegisterSocketBallCountListner();

        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mode_ball_s5;
    }

    @Override
    protected void initView() {

        rightTV.setText(R.string.setting);

        //记录当前亮度
        oriBright = getScreenBright();
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        modeName = intent.getStringExtra("modeName");
        data = intent.getCharArrayExtra("data");
        isTime = intent.getBooleanExtra("isTime", false);
        time = intent.getIntExtra("time", 0);
        count = intent.getIntExtra("count", 0);

        titleTV.setText(modeName);
        if (isTime) {
            hintTimeTV.setText(R.string.rest_time);
            hintCountTV.setText(R.string.ball_count);
        } else {
            hintTimeTV.setText(R.string.ball_time);
            hintCountTV.setText(R.string.rest_ball);
        }

        DeviceBean deviceBean = SocketManager.getInstance().getCurDeviceBean();
        if (deviceBean != null && deviceBean.getAlias() != null) {
            deviceNameTV.setText(deviceBean.getAlias());
        }
        registerSocketBallCountListner();
        startBall();
    }

    @Override
    protected void initListener() {
        //监听app前后台
        EventBus.getDefault().register(this);

        startTV.setOnClickListener(new DebounceOnClickListener() {
            @Override
            protected void onClickView(View view) {
                //任何按钮被点击，都还原亮度
                setScreenBright(oriBright);
                //一段时间后，减少亮度
                autoBright();

                startBall();
            }
        });

        stopTV.setOnClickListener(new DebounceOnClickListener() {
            @Override
            protected void onClickView(View view) {
                //任何按钮被点击，都还原亮度
                setScreenBright(oriBright);
                //一段时间后，减少亮度
                autoBright();

                stopBall();
            }
        });

        if (AppCacheUtil.getInstance().getS3Ors5Type() == ModeConstant.DeviceTypeS3) {
            unloadTV.setVisibility(View.VISIBLE);
            unloadTV.setOnClickListener(new DebounceOnClickListener() {
                @Override
                protected void onClickView(View view) {
                    //任何按钮被点击，都还原亮度
                    setScreenBright(oriBright);
                    //显示弹窗
                    showUnloadAlert();
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 超5的后台运行方案 默认0
        int bgPrograme = AppCacheUtil.getInstance().getBgProgram();
        if (bgPrograme != 0) {
            return;
        }
        // 超5的后台运行方案 亮度
        keepScreenBright(true);

        //恢复亮度
        setScreenBright(oriBright);
        //一段时间后，减少亮度
        autoBright();
    }

    @Override
    protected void onPause() {
        super.onPause();

        keepScreenBright(false);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            //任何按钮被点击，都还原亮度
            setScreenBright(oriBright);
            //一段时间后，减少亮度
            autoBright();
        }

        if (unloadState == 1) {
            //卸球中
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            //任何屏幕的位置被点击，都还原亮度
            setScreenBright(oriBright);
            //一段时间后，减少亮度
            autoBright();
        }
        return super.onTouchEvent(event);
    }

    private void startBall() {
        if (data == null) {
            showToast(getString(R.string.params_err));
            return;
        }
        SocketManager.getInstance().sendData(data);

        progressView.setProgress(0);

        ballTime = 0;
        offsetCount = 0;
        if (isTime) {
            countTV.setText("0");
        } else {
            countTV.setText("" + count);
        }
        startTimer();
    }

    private void stopBall() {
        char[] stopData = DFS5ProtocolMaker.stop();
        SocketManager.getInstance().sendData(stopData);
        stopTimer();
    }

    private void registerSocketBallCountListner() {
        SocketManager.getInstance().setOnSocketBallCountListner(new SocketManager.OnSocketBallCountListner() {
            @Override
            public void onBallCount(int count1) {
                if (offsetCount == 0) {
                    offsetCount = count1;
                }
                int curCount = count1 - offsetCount + 1;
                if (curCount <= 0) {
                    curCount = count1 - offsetCount + 1 + 9999; // 球数最大值为9999
                }

                if (isTime) {
                    //按时间来发球  显示的的球数的正数的
                    countTV.setText("" + curCount);
                } else {
                    //按发球数来发球  显示的的球数的倒数的
                    if (curCount >= S5ModeBallActivity.this.count) {
                        progressView.setProgress(100);
                        countTV.setText("0");
                        stopBall();
                    } else {
                        progressView.setProgress(curCount * 100 / count);
                        countTV.setText("" + (S5ModeBallActivity.this.count - curCount));
                    }
                }
            }
        });
    }

    private void unRegisterSocketBallCountListner() {
        SocketManager.getInstance().setOnSocketBallCountListner(null);
    }

    @OnClick(R.id.tv_back)
    public void onBackClick() {
        finish();
    }

    @OnClick(R.id.tv_right)
    public void onRightBtnClick(){
        Intent intent = new Intent(this, S5ModeSettingActivity.class);
        startActivity(intent);
    }

    //region 卸球
    private int unloadState = 0;  //0.默认状态 1.当前正在卸球
    private void showUnloadAlert() {
        //恢复亮度
        lockCounter++;
        setScreenBright(oriBright);

        unloadState = 0;
        String title = getString(R.string.unload_alert);
        String content = getString(R.string.unload_alert_2);
        CommonDialog dialog = new CommonDialog(this, title, content, new CommonDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (unloadState == 0) {
                   // 默认状态
                    if (confirm) {
                        //停止读取发球数
                        stopTimer();

                        CommonDialog dialog1 = (CommonDialog)dialog;
                        //修改UI
                        String title2 = getString(R.string.stop_unload_alert);
                        String content2 = getString(R.string.stop_unload_alert_2);
                        dialog1.setTitle(title2);
                        dialog1.setContent(content2);
                        dialog1.setPositiveButton(getString(R.string.stop_unload));
                        dialog1.setShowNegativeButton(false);
                        dialog1.refreshUI();

                        //开始卸球
                        unloadState = 1;
                        startUnload();
                    } else {
                        lockCounter--;
                        autoBright();
                        dialog.dismiss();
                    }
                } else {
                   // 当前正在卸球
                    lockCounter--;
                    autoBright();
                    dialog.dismiss();
                    //停止卸球
                    unloadState = 0;
                    stopUnload();
                }
            }
        });
        dialog.setPositiveButton(getString(R.string.unload));
        dialog.setAutoDismissWhenClick(false);
        dialog.show();
    }

    //开始卸球
    private void startUnload() {
        char[] unloadData = DFS5ProtocolMaker.unload();
        SocketManager.getInstance().sendData(unloadData);
    }

    //停止卸球
    private void stopUnload() {
        char[] stopUnloadData = DFS5ProtocolMaker.stopUnload();
        SocketManager.getInstance().sendData(stopUnloadData);
    }

    //endregion

    //region 定时器
    private void startTimer() {
        if (timer != null) {
            return;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                timerAction();
            }
        }, 0, 1000);
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void timerAction() {

        try {
            if (isTime) {
                //按时长发球  显示的时间是倒计时
                if (ballTime >= time) {
                    progressView.setProgress(100);
                    timeTV.setText("00:00");
                    stopBall();
                    return;
                } else {
                    int restTime = time - ballTime;
                    int h = restTime / 3600;
                    int m = (restTime - (3600 * h)) / 60;
                    int s = restTime % 60;
                    if (h == 0) {
                        timeTV.setText(String.format(Locale.getDefault(), "%02d:%02d", m, s));
                    } else {
                        timeTV.setText(String.format(Locale.getDefault(), "%02d:%02d:%02d", h, m, s));
                    }
                    progressView.setProgress(ballTime * 100 / time);
                }
            } else {
                //按发球数发球  显示的时间是正向计时
                int h = ballTime / 3600;
                int m = (ballTime - (3600 * h)) / 60;
                int s = ballTime % 60;
                if (h == 0) {
                    timeTV.setText(String.format(Locale.getDefault(), "%02d:%02d", m, s));
                } else {
                    timeTV.setText(String.format(Locale.getDefault(), "%02d:%02d:%02d", h, m, s));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ballTime += 1;
    }
    //region

    //保持屏幕常亮
    private void keepScreenBright(boolean bright) {
        if (bright) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }
    //获取屏幕亮度
    private float getScreenBright() {
//        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
//        return layoutParams.screenBrightness;

        return BrightnessTools.getScreenBrightness(this);
    }

    //设置屏幕亮度
    private void setScreenBright(float bright) {
        BrightnessTools.setBrightness(this, bright);
    }
    //一段时间后，减少亮度
    private void autoBright() {
        lockCounter++;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                lockCounter--;
                if (lockCounter <= 0 && !isDestroyed()) {
                    // 超5的后台运行方案 亮度
                    float bgLight = AppCacheUtil.getInstance().getBgLight();
                    if (bgLight >= 0.3) {
                        bgLight = 0.3f;
                    }
                    setScreenBright(bgLight);
                }
            }
        }, 5000);
    }

    //region app是否进入前后台
    private void onAppForegrounded() {
        SocketManager.getInstance().setBackground(false);
        // 关闭 后台可能存在的音频
        SocketManager.getInstance().stopSilentMp3IfNeeded();
    }

    private void onAppBackgrounded() {
        SocketManager.getInstance().setBackground(true);
        // 后台运行 可能需要播放音频
        SocketManager.getInstance().playSilentMp3IfNeeded();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (MessageEvent.APP_BACKGROUND.equals(event.getTag())) {
            onAppBackgrounded();
        } else if (MessageEvent.APP_FOREGROUND.equals(event.getTag())) {
            onAppForegrounded();
        }
    }

    //endregion
}
